package com.wtwd.wtwddevice.service.impl;


import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtwd.device.util.DateUtils;
import com.wtwd.wtwddevice.mapper.DeviceStepMapper;
import com.wtwd.wtwddevice.model.entity.DeviceStep;
import com.wtwd.wtwddevice.model.entity.DeviceStepInfo;
import com.wtwd.wtwddevice.service.IDeviceStepInfoService;
import com.wtwd.wtwddevice.service.IDeviceStepService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 每日步数 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2024-05-25
 */
@Service
public class DeviceStepServiceImpl extends ServiceImpl<DeviceStepMapper, DeviceStep> implements IDeviceStepService {

    @Resource
    private DeviceStepMapper stepMapper;

    @Resource
    private IDeviceStepInfoService stepInfoService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DeviceStepInfo synchronization(Long deviceId, Integer stepNum, String time, int type, String number) {
        String dateTime = DateUtils.convertDateFormat(time);
        DeviceStep deviceStep = getDeviceStepByTimeOne(deviceId, dateTime);
        boolean flag = true;
        if (deviceStep == null) {//插入
            deviceStep = new DeviceStep();
            deviceStep.setDeviceId(deviceId);
            deviceStep.setTime(dateTime);
            deviceStep.setType(type);
            deviceStep.setTotalSteps(stepNum);
            deviceStep.setNumber(number);
            save(deviceStep);
        } else {
            deviceStep.setTime(dateTime);
            deviceStep.setType(type);
            deviceStep.setTotalSteps(stepNum);
            deviceStep.setNumber(number);
            flag = false;
        }
        DeviceStepInfo stepInfo = new DeviceStepInfo();
        BeanUtils.copyProperties(deviceStep, stepInfo);
        stepInfo.setId(null);
        stepInfo.setDeviceStepId(deviceStep.getId());
        stepInfo.setTime(time);
        boolean save = stepInfoService.save(stepInfo);
        if (save) {
            deviceStep.setLastInfoId(stepInfo.getId());
            updateById(deviceStep);
        }
        return stepInfo;
    }

    @Override
    public boolean insertOrUpdate(DeviceStep step) {
        if (step == null) {
            return false;
        }
        return stepMapper.insertOrUpdate(step) > 0 ? true : false;
    }

    @Override
    public DeviceStep getDeviceStepByTimeOne(Long deviceId, String time) {
        return new LambdaQueryChainWrapper<>(stepMapper)
                .eq(DeviceStep::getDeviceId, deviceId)
                .eq(DeviceStep::getTime, time)
                .one();
    }
}
